package cn.xiaoyu.su.controller;


import cn.xiaoyu.su.annotation.RepeatSubmit;
import cn.xiaoyu.su.constant.CacheKey;
import cn.xiaoyu.su.controller.request.ConfirmOrderRequest;
import cn.xiaoyu.su.controller.request.OrderPageRequest;
import cn.xiaoyu.su.enums.BizCodeEnum;
import cn.xiaoyu.su.enums.ClientTypeEnum;
import cn.xiaoyu.su.enums.ProductOrderPayTypeEnum;
import cn.xiaoyu.su.interceptor.LoginInterceptor;
import cn.xiaoyu.su.service.ProductOrderService;
import cn.xiaoyu.su.util.CommonUtil;
import cn.xiaoyu.su.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ⼆当家⼩D
 * @since 2022-12-18
 */
@RestController
@RequestMapping("/api/order/v1")
@Slf4j
public class ProductOrderController {

    @Autowired
    private ProductOrderService productOrderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 下单前获取令牌，用于防重提交
     * @return
     */
    @GetMapping("token")
    public JsonData getOrderToken(){

        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();

        String token = CommonUtil.getStringNumRandom(32);

        String key = String.format(CacheKey.SUBMIT_ORDER_TOKEN_KEY, accountNo, token);

        //令牌有效时间是30分钟
        redisTemplate.opsForValue().set(key, String.valueOf(Thread.currentThread().getId()),30, TimeUnit.MINUTES);

        return JsonData.buildSuccess(token);

    }

    /**
     * 分页接口
     * @param orderPageRequest
     * @return
     */
    @PostMapping("page")
    public JsonData page(@RequestBody OrderPageRequest orderPageRequest) {

        Map<String,Object> pageResult = productOrderService.page(orderPageRequest);
        return JsonData.buildSuccess(pageResult);
    }

    /**
     * 查询订单状态
     * @param outTradeNo
     * @return
     */
    @GetMapping("query_state")
    public JsonData queryState(@RequestParam(value = "out_trade_no")String outTradeNo){

        String state = productOrderService.queryProductOrderState(outTradeNo);

        return StringUtils.isBlank(state) ? JsonData.buildResult(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) : JsonData.buildSuccess(state);

    }

    /**
     * 下单
     * @param confirmOrderRequest
     * @return
     */
    @PostMapping("confirm")
    //@RepeatSubmit(limitType = RepeatSubmit.Type.PARAM)
    public void confirmOrder(@RequestBody ConfirmOrderRequest confirmOrderRequest, HttpServletResponse response) {

        JsonData jsonData = productOrderService.confirmOrder(confirmOrderRequest);

        if (jsonData.getCode() == 0){

            //端类型
            String clientType = confirmOrderRequest.getClientType();
            //支付类型
            String payType = confirmOrderRequest.getPayType();

            if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALI_PAY.name())) {
                //如果是支付宝支付，跳转网页,sdk除外
                if (clientType.equalsIgnoreCase(ClientTypeEnum.PC.name())){

                    CommonUtil.sendHtmlMessage(response,jsonData);
                }else if (clientType.equalsIgnoreCase(ClientTypeEnum.APP.name())){

                }else if (clientType.equalsIgnoreCase(ClientTypeEnum.H5.name())){

                }

            } else if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.WECHAT_PAY.name())) {
                //微信支付
                CommonUtil.sendJsonMessage(response,jsonData);
            }

        } else {

            log.error("创建订单失败{}",jsonData.toString());
        }


    }
}

